<?php
define( "DB_SERVER",    getenv('OPENSHIFT_MYSQL_DB_HOST') );
define( "DB_USER",      getenv('OPENSHIFT_MYSQL_DB_USERNAME') );
define( "DB_PASSWORD",  getenv('OPENSHIFT_MYSQL_DB_PASSWORD') );
define( "DB_DATABASE",  getenv('OPENSHIFT_APP_NAME') );

$database = DB_DATABASE;

mysql_connect(DB_SERVER,DB_USER,DB_PASSWORD) or die('cant connect to database');
mysql_select_db(DB_DATABASE) or die("Unable to select database");

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

if ($putdata = fopen("php://input", "rb"))
    {
        $json = "";
        while ($data = fread($putdata, 1024))
        {
            $json .= $data;
        }
        fclose($putdata);

    } else
    {
        echo '<record>';
        header("HTTP/1.1 500 Internal Server Error");
        echo "** Error opening received file<br>\n";
        echo '</record>';
        return;
    }

	$obj = json_decode($json);
    $query = "SELECT regid FROM gcm WHERE userid = '" . $obj->{'androidId'} . "'; " ;
    $result = mysql_query($query) or die("Error");
    if( !$result) die("Error");
    $row = mysql_fetch_assoc($result);
    if( !$row) die("Error");
    $regid =$row['regid'];
    if( !$regid) die("Error");
	$headers = array('Authorization:key=AIzaSyDELYmcizyFmy9gYNkT_fYhMD-7jLHDIew'); 
    date_default_timezone_set('Europe/Moscow');
    $mes = $obj->{'message'} . " - From " . $obj->{'board'} . " at " . date('H:i:s d-m-Y ');
    $data = array(  
        'registration_id' => $regid,  
        'data.message' => $mes );
  
    $ch = curl_init();  
  
    curl_setopt($ch, CURLOPT_URL, "https://android.googleapis.com/gcm/send");  
    if ($headers)  
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);  
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  
    curl_setopt($ch, CURLOPT_POST, true);  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);  
  
    $response = curl_exec($ch);  
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);  
    curl_close($ch);
}  

?>
